/**
 * @file show_data.js
 * @author Jasper0819X
 * @date 2018/2/11
 */
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}
//20181114
// function export_data(did, type) {
//   $.get(Urls.resolve('api_v1_storage:data_file'), {
//     type: type,
//     oid: did
//   }).done(function (resp) {
//     var fmts = gettext('Data successfully exported! Click %s here %s or `Download` button to download it.');
//     $.showModal({
//       title: gettext('Success'),
//       message: interpolate(fmts, ['<a target="_blank" href="' + resp.data.file + '"><b>', '</b></a>']),
//       onOk: function () {
//         window.open(resp.data.file);
//       },
//       okText: gettext('Download')
//     });
//   }).fail(function (resp) {
//     if(resp.status === 401){
//       var next = window.location.href.replace(window.location.origin, '');
//       window.location.href = Urls.resolve('account:login') + '?next=' + next;
//     }
//     else {
//       $.showModal({
//         message: resp.responseJSON.msg
//       });
//     }
//   });
// }
//20181114
// store container tp
//$.savedTp = {};

//$.asyncUpdateList = [];

function tableRender(tp, data) {
  var head = tp._head;
  var thead = '<thead align="center"> <tr> <th>#</th>';
  // head
  for (var i = 0; i < head.length; ++i) {
    thead += '<th>' + head[i] + '</th>';
  }
  thead += '</tr> </thead>';

  var body = data;
  var tbody = '<tbody>';
  for (var i = 0; i < body.length; ++i) {
    tbody += '<tr> <th scope="row">' + (i + 1) + '</th>';
    for (var j = 0; j < head.length; ++j) {
      tbody += '<td>' + itemRender('', tp[head[j]], data[i][head[j]]) + '</td>'
    }
    tbody += '</tr>';
  }
  tbody += '</tbody>';
  return '<div class="table-responsive"><table class="table table-striped table-bordered table-condensed">' + '<caption>' + (data.title || '') + '</caption>' + thead + tbody + '</table></div>';
}

/*
function panelUpdate(id) {
  var view_id = '#' + id;
  var ctype = $(view_id).attr('content_type');
  if (ctype === 'table') {
    $.get(Urls.resolve('api_v1_storage:data_field_table_one', {tid: id}), '', function (data) {
      $(view_id).html('<div class="panel-body">' + tableRender($.savedTp[id], data.data) + '</div>');

      if($.asyncUpdateList.length > 0){
        panelUpdate($.asyncUpdateList.shift());
      }
    });
  }
  else if (ctype === 'container') {
    $.get(Urls.resolve('api_v1_storage:data_field_container_one', {cid: id}), '', function (data) {
      $(view_id).html('<div class="panel-body">' + DataRender($.savedTp[id], data.data) + '</div>');

      if($.asyncUpdateList.length > 0){
        panelUpdate($.asyncUpdateList.shift());
      }
    });
  }
  $(view_id).html('<div class="panel-body"></div>');
}
*/

function primitiveRender(title, data) {
  return '<div class="dl-horizontal">'
    + '<dt>' + title + '</dt>' + '<dd>' + data + '</dd>'
    + '</div>';
}

function stringRender(title, data, suffix) {
  if (!title) {
    return '<div class="item-card">'
      + '<div class="content">' + data + suffix + '</div>'
      + '</div>'
  }
  return '<div class="item-card">'
    + '<div class="title">' + title + ': ' + '</div>'
    + '<div class="content">' + data + suffix + '</div>'
    + '</div>'
}

function panelRender(tp, title, data, content_type) {
  var id = $.getUniqueId();
  title = title || gettext('Item');

  var panel_body = '';
  if (content_type === 'table') {
    panel_body = '<div class="panel-body">' + tableRender(tp, data) + '</div>';
  }
  else if (content_type === 'container') {
    panel_body = '<div class="panel-body">' + DataRender(tp, data) + '</div>'
  }

  var content = '<div class="panel panel-default">'
    + '  <div class="panel-heading">'
    + '    <h4 class="panel-title">'
    + '      <a data-toggle="collapse" href="#' + id + '">' + title + '</a>'
    + '    </h4>'
    + '  </div>'
    + '  <div id="' + id + '" class="panel-collapse collapse in" content_type="' + content_type + '">'
    + panel_body
    + '  </div>'
    + '</div>';
  //$.asyncUpdateList.push(id)
  return content;
}

function picturesRender(title, tp, data) {
  if (data == null) return '';
  if (data.length === 0) return '';
  var id = guid();
  var imgs = '';
  if (tp.multi) {
    // 多张
    for (var i = 0; i < data.length; ++i) {
      var url = data[i];
      imgs += '<img class="img-responsive" src="' + url + '" alt="">';
    }
  }
  else {
    // 单张
    imgs = '<img class="img-responsive" src="' + data + '" alt="">'
  }

  return '<div class="panel panel-default">'
      + '  <div class="panel-heading">'
      + '    <h4 class="panel-title">'
      + '      <a data-toggle="collapse" href="#' + id + '">' + title + '</a>'
      + '    </h4>'
      + '  </div>'
      + '  <div id="' + id + '" class="panel-collapse collapse in">' + imgs
      + '  </div>'
      + '</div>';
}

function filesRender(title, tp, data) {
  if (data == null) return '';
  if (data.length === 0) return '';
  if (title.length === 0) title = gettext('File');
  
  if(tp.multi){
    var id = guid();
    var files = '';
    for (var i = 0; i < data.length; ++i) {
      var url = data[i];
      files += '<a href="' + url + '">file' + i + '</a>&nbsp;';
    }
    return '<div class="panel panel-default">'
      + '  <div class="panel-heading">'
      + '    <h4 class="panel-title">'
      + '      <a data-toggle="collapse" href="#' + id + '">' + title + '</a>'
      + '    </h4>'
      + '  </div>'
      + '  <div id="' + id + '" class="panel-collapse collapse in">'
      + '    <div class="panel-body">' + files + '</div>'
      + '  </div>'
      + '</div>';
  }
  else {
    return '<div class="panel panel-default">'
      + '  <div class="panel-body"><a href="' + data + '">' + title + '</a></div>'
      + '</div>';
  }
}

function arrayRender(title, tp, data) {
  if (!data) return '';
  var content = '';
  for (var i = 0; i < data.length; ++i) {
    content += itemRender('', tp, data[i]);
  }

  var id = $.getUniqueId();
  return '<div class="panel panel-default">'
    + '  <div class="panel-heading">'
    + '    <h4 class="panel-title">'
    + '      <a data-toggle="collapse" href="#' + id + '">' + title + '</a>'
    + '    </h4>'
    + '  </div>'
    + '  <div id="' + id + '" class="panel-collapse collapse in">'
    + '    <div class="panel-body">' + content + '</div>'
    + '  </div>'
    + '</div>';
}

function itemRender(name, tp, data) {
  if (data == null) return '';
  tp.misc = tp.misc || {};
  // 字符串和选项
  if (tp.t === 1 || tp.t === 6) return stringRender(name, data, '');
  // 数值
  if (tp.t === 2) return stringRender(name, data, (tp.misc.unit == null ? '' : tp.misc.unit));
  // 范围
  if (tp.t === 3) {
    if (tp.misc.type === 0) {
      var ub = (data.ub == null ? '?' : data.ub);
      var lb = (data.lb == null ? '?' : data.lb);
      return stringRender(name, lb + '~' + ub, (tp.misc.unit == null ? '' : tp.misc.unit));
    }
    else if (tp.misc.type === 1) {
      var val = (data.val == null ? '?' : data.val);
      var err = (data.err == null ? '?' : data.err);
      return stringRender(name, val + '±' + err, (tp.misc.unit == null ? '' : tp.misc.unit));
    }
    else return ''; // error type
  }
  // 图片
  if (tp.t === 4) return picturesRender(name, tp.misc, data);
  // 文件
  if (tp.t === 5) return filesRender(name, tp.misc, data);
  // 数组
  if (tp.t === 7) return arrayRender(name, tp.misc, data);
  // 表格
  if (tp.t === 8) {
    //$.savedTp[data] = tp.misc;
    return panelRender(tp.misc, name, data, 'table');
  }
  // 容器
  if (tp.t === 9) {
    //$.savedTp[data] = tp.misc;
    return panelRender(tp.misc, name, data, 'container')
  }
  // 生成器
  if (tp.t === 10) {
    return itemRender(data.sel, tp.misc[data.sel], data.val);
  }
}

// template包含_ord和必要的键值。
function DataRender(template, data) {
  var result = '';
  for (var i = 0; i < template._ord.length; ++i) {
    var field = template._ord[i];
    result += itemRender(field, template[field], data[field]);
  }
  return result;
}

function recommendPanel(dm){
  var times=dm.add_time.split('.')[0].split('T');
  var add_time=times[0]+' '+times[1];
  return '<div class="col-lg-3 col-md-3 hidden-xs hidden-sm">'+
      '<p><a target="_blank" href="' + Urls.resolve('storage:show_data', {did: dm.id}) + '" title="' + gettext('View') + '">' + dm.title + '</a></p>' +
      '<p><span class="dt">' + gettext('Abstract') + '</span><span class="dd">' + dm.abstract + '</span></p>' +
      '<p><span class="dt">'+gettext('Material Class')+'</span><span class="dd">'+dm.category_name+'</span></p>'+
      '<p><span class="dt">'+gettext('Views')+'</span><span class="dd">'+dm.views+'</span></p>'+
      '<p><span class="dt">'+gettext('Add Time')+'</span><span class="dd">'+add_time+'</span></p>'+
      '</div>'
}

function recommend(id){
    $.get(Urls.resolve('storage_api_v1:recommend'),{
      'id':id
    }).done(function (resp) {
      console.log(resp.data);
      var scope=$('#scope');
      // var firstScope=$('#first-scope');
      // var seconfScope=$('#second-scope');
      // $.each(resp.data.results, function (i, it) {
          // console.log(i);
          // if(i<=2){
          //   firstScope.append(recommendPanel(it));
          // }
          // else{
          //   seconfScope.append(recommendPanel(it));
          // }
      // });
      resp.data.results.forEach(function (it) {
        scope.append(recommendPanel(it));
      });
    }).fail(function () {
      window._jqHandled = true;
    });
}

$(function () {
  function setBasicInfo(data) {
    var keywordsRender = doT.template(
      '{{~it :value:index}}' +
      '<span class="label label-info">{{=value}}</span>&nbsp;' +
      '{{~}}'
    );
    $('#d-title').text(data.title || '');
    var times=data.add_time.split('.')[0].split('T');
    var add_time=times[0]+' '+times[1];
    // console.log(add_time);
    $('#d-datetime').text(add_time || '');
    $('#d-keywords').html($.parseHTML(keywordsRender(data.keywords)));
    $('#d-author').text(data.author || '');
    $('#d-abstract').text(data.abstract || '');
  }

  /*
  function setContentInfo(data) {
    $.requestJSON({
      method: 'GET',
      url: Urls.resolve('api_v1_storage:template_one', {tid: data.tid}),
      onSuccess: function (temp_json) {
        $('#data-content-inner').html(DataRender(temp_json.data.content, data.content));
        if($.asyncUpdateList.length > 0){
          panelUpdate($.asyncUpdateList.shift());
        }
      },
      onError: function (json) {
        console.log(json);
      }
    });
  }
  */

  function setSourceInfo(data) {
    $('#d-src-src').text(data.source.source || '');
    $('#d-src-proj').text(data.source.project || '');
    if(data.source.reference!=null){
        var ref=data.source.reference.split('|');
        // console.log(ref);
        var obj='<ol>';
        ref.forEach(function (it) {
            obj += '<li>'+it + '</li>';
        });
        obj+='</ol>';
        $('#d-src-ref').html(obj);
    }
    else{
      $('#d-src-ref').text('');
    }
    $('#d-src-others').text(data.source.others || '');
    //fsch——产生推荐：
    console.log(data.id);
    recommend(data.id);
  }

  $.requestJSON({
    method: 'GET',
    url: Urls.resolve('storage_api_v1:metadata_detail', { pk: window.location.href.split('/').pop() }),
    onSuccess: function (json) {
      console.log(json);
      setBasicInfo(json.data);
      //setContentInfo(json.data);
        //最新注释 显示模板的具体内容
      $('#data-content-inner').html(DataRender(json.data.template.content, json.data.content));
      console.log(json.data.template.content, json.data.content);
      setSourceInfo(json.data);
    },
    onError: function () {
      window._jqHandled = true;
    }
  });

});
